<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 幕小铺科技（大连）有限公司 [ http://www.XXX.com ]
// +----------------------------------------------------------------------
// | 2020/03/14 jason wang
// +----------------------------------------------------------------------
namespace app\erp\logic;
use app\erp\model\ErpEvaluate;
use think\facade\Hook;
use think\DB;
use util\Tree;
use think\facade\Debug;
use think\facade\Cache;
/**
 * 门评价管理
 * @package app\erp\model
 */
class Evaluatelogic{

    /**
     * 首页
     * @author  dou<51779987@qq.com>
     * @return array_out(code, message, data)
     */
    public function evaluate_index($user_id, $goods_id, $score = '', $uid = '', $createTime =''){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' => $user_id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
            $map = [];//搜索处理
            if($goods_id != '')     $map[] = ['goods_id','=',$goods_id];
            if($score != '')        $map[] = ['score','=',$score];
            if($uid != '')          $map[] = ['uid','=',$uid];
            if($createTime != '')   $map[] = ['create_time','=',$createTime];
			$list =  model('ErpEvaluate', 'model') -> where($map) -> order('create_time desc')->paginate();//获取列表
			$rel_list = [];
            foreach($list as $key => $value){
				$rel_list[$key]['id'] 			    = (int)$value['id'];
				$rel_list[$key]['goodsId'] 		    = (int)$value['goods_id'];
                //$goodsInfo                          = controller('Goodslogic', 'logic') -> getGoodsInfo($value['goods_id']);
				//$rel_list[$key]['goodsInfo'] 		= $goodsInfo['data'];
				$rel_list[$key]['score'] 	        = (string)$value['score'];
				$rel_list[$key]['spbzScore'] 	    = $value['spbz_score'] == '' ? 0 : (string)$value['spbz_score'];
				$rel_list[$key]['qifwScore'] 	    = $value['qifw_score'] == '' ? 0 : (string)$value['qifw_score'];
				$rel_list[$key]['uid']              = (int)$value['uid'];
				//获取用户信息
                $userInfo                           = controller('user_center/Userlogic', 'logic\user') -> get_user_info($value['uid'],$value['uid']);
                $rel_list[$key]['userInfo'] 		= $userInfo['data'];
				$rel_list[$key]['content']          = (string)$value['content'];
				$rel_list[$key]['createTime'] 		= (int)$value['create_time'];
				$rel_list[$key]['updateTime'] 		= (int)$value['update_time'];
				//查找图片
                $evaluate_imgs = model('ErpEvaluateImg') -> where(['evaluate_id'=>$value['id']])->select()->toArray();
                if($evaluate_imgs){
                    foreach($evaluate_imgs as $k_img=>$v_img){//dump($v_img);
                        $rel_list[$key]['evaluateImgs'][$k_img]['id']            = (int)$v_img['id'];
                        $rel_list[$key]['evaluateImgs'][$k_img]['evaluateId']    = (int)$v_img['evaluate_id'];
                        $rel_list[$key]['evaluateImgs'][$k_img]['imgUrl']        = (string)$v_img['img_url'];
                        $rel_list[$key]['evaluateImgs'][$k_img]['createTime']    = (int)$v_img['create_time'];
                        $rel_list[$key]['evaluateImgs'][$k_img]['updateTime']    = (int)$v_img['update_time'];
                    }
                }

			}
            $result_list = [];
            $result_list['total']  			= (int)$list -> total();//总数
            $result_list['current_page']	= (int)$list -> currentPage();//页码
            $result_list['last_page']   	= (int)$list -> lastPage();//总页数
            $result_list['per_page']   		= (int)$list -> listRows();//每页条数
            $result_list['data'] 			= $rel_list;
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $result_list);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 添加
     * @param goods_id 	            int     商品id
     * @param score 		        float   评分
     * @param content 		        string  内容
     * @param uid 		            int     评论人id
     * @param create_time 		    string  创建时间
     * @param update_time 		    string  编辑时间
     * @param evaluate_imgs 		array  评论图片（数组，最多9张）
     * @author dou<51779987@qq.com>
     * @return array_out(code, message, data)
     */
    public function add($user_id, $goods_id, $score, $content, $uid, $evaluate_imgs, $order_id, $spbz_score, $qifw_score, $sku_id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	        => $user_id,
				'goods_id'          => $goods_id,
                'score'             => $score,
                'content' 	        => $content,
                'uid' 	            => $uid,
                'evaluate_imgs'     => $evaluate_imgs,
                'spbz_score'     	=> $spbz_score,
                'qifw_score'     	=> $qifw_score,
                'order_id'     		=> $order_id,
                'sku_id'     		=> $sku_id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			$rel = model('ErpEvaluate') -> addData($goods_id, $score, $content, $uid, $order_id, $spbz_score, $qifw_score, $sku_id);//添加
            if($rel['code'] == 200){
                //附属图片（直接添加）
				if($evaluate_imgs != ''){
					$evaluate_imgs = json_decode($evaluate_imgs, true);
					$rel = model('ErpEvaluateImg') -> addDataImg($rel['data'], $evaluate_imgs);//添加
					if($rel['code'] < 0){
						DB::rollback();
						return array_out(-1005, 'error');//添加失败 返回-1005,error
					}
				}
            }else{
                DB::rollback();
                return array_out(-1005, 'error');//添加失败 返回-1005,error
            }
            /********业务逻辑********/

            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success',$rel['data']);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 编辑
     * @param id 	                int     评论id
     * @param goods_id 	            int     商品id
     * @param score 		        float   评分
     * @param content 		        string  内容
     * @param uid 		            int     评论人id
     * @param create_time 		    string  创建时间
     * @param update_time 		    string  编辑时间
     * @param evaluate_imgs 		array  评论图片（数组，最多9张）
     * @author dou<51779987@qq.com>
     * @return array_out(code, message, data)
     */
    public function edit($user_id, $id,$goods_id, $score, $content, $uid, $evaluate_imgs, $spbz_score, $qifw_score,$sku_id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	        => $user_id,
				'id' 		        => $id,
                'goods_id'          => $goods_id,
                'score'             => $score,
                'content' 	        => $content,
                'uid' 	            => $uid,
                'evaluate_imgs'     => $evaluate_imgs,
				'spbz_score'     	=> $spbz_score,
                'qifw_score'     	=> $qifw_score,
                'sku_id'     	    => $sku_id,
            ];

            /********行为参数赋值（*）********/

            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			
			$rel = model('ErpEvaluate') -> editData($id,$goods_id, $score, $content, $uid, $spbz_score, $qifw_score, $sku_id);
            if($rel['code'] == 200){
                //附属图片（先清空再添加）
                $rel = model('ErpEvaluateImg') -> deleteDataImg($id);//清空图片
                if($rel['code'] == 200){
                    $rel = model('ErpEvaluateImg') -> addDataImg($id, $evaluate_imgs);//添加
                    if($rel['code'] < 0){
                        DB::rollback();
                        return array_out(-1005, 'error');//添加失败 返回-1005,error
                    }
                }else{
                    DB::rollback();
                    return array_out(-1005, 'error');//删除失败 返回-1005,error
                }
            }else{
                DB::rollback();
                return array_out(-1005, 'error');//添加失败 返回-1005,error
            }
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 删除
     * @param int $id
     * @author dou<51779987@qq.com>
     * @return bool
     */
    public function delete($user_id, $id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'id' 		=> $id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			$rel = model('ErpEvaluate') -> deleteData($id);
            if($rel['code'] == 200){
                //附属图片（先清空再添加）
                $rel = model('ErpEvaluateImg') -> deleteDataImg($id);//清空图片
                if($rel['code'] == 200){
                }else{
                    DB::rollback();
                    return array_out(-1005, 'error');//删除失败 返回-1005,error
                }
            }else{
                DB::rollback();
                return array_out(-1005, 'error');//删除失败 返回-1005,error
            }
			
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 删除
     * @param int $id
     * @author dou<51779987@qq.com>
     * @return bool
     */
    public function deleteImg($user_id, $id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
                'user_id' 	=> $user_id,
                'id' 		=> $id,
            ];
            /********行为参数赋值（*）********/

            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
            $rel = model('ErpEvaluateImg') -> deleteData($id);//删除图片
            if($rel['code'] == 200){
            }else{
                DB::rollback();
                return array_out(-1005, 'error');//删除失败 返回-1005,error
            }

            /********业务逻辑********/

            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
            DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/

        } catch (\Exception $e) {
            DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 根据goods_id查看评论
     * @param int $id
     * @author dou<51779987@qq.com>
     * @return bool
     */
    public function getListByGoodsid($goods_id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'goods_id' 	=> $goods_id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

           
            /********业务逻辑********/
            $list = $this -> evaluate_index($user_id = 0, $goods_id);
            if($list['code'] == 200) $rel_list = $list['data'];

            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
            DB::commit();
            if(isset($rel_list)){
                return array_out(200, 'success', $rel_list);
            }
            
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
}